import React, {Component, createContext} from 'react';
import './contextLol.css'
import XEUtils from "xe-utils";
const MyContext = createContext({}) //创建Context

class A extends Component {
    render() {
        return <div className={"kua-zu-jian a"}>
            我是a
            <B></B>
        </div>;
    }
}

class B extends Component {
    //contextType 名字是固定的
    static contextType = MyContext //定义接收参数
    get(obj,field){
        return XEUtils.get(obj,field)
    }
    render() {
        return <div className={"kua-zu-jian b"}>我是B
        <C></C>
            接收最高组件的参数：{this.get(this,'context.name')}-{this.get(this,'context.age')}
        </div>;
    }
}

class C extends Component {
    static contextType = MyContext //定义接收参数

    get(obj,field){
        return XEUtils.get(obj,field)
    }

    render() {
        return <div className={"kua-zu-jian c"}>
            我是C
            接收最高组件的参数：{this.get(this,'context.name')}-{this.get(this,'context.age')}
        </div>;
    }
}

class ContextLolClass extends Component {
    state = {
        user: {
            age: 18,
            name: '小李'
        }
    }

    render() {
        return (
            <div>
                <div className={"kua-zu-jian"}>
                    我是最高组件 {this.state.user.name}-{this.state.user.age}
                    <button onClick={this.add}>加</button>
                    {/*指定这里的组件可以使用Context*/}
                    <MyContext.Provider value={this.state.user}>
                        <A></A>
                    </MyContext.Provider>
                </div>
            </div>
        );
    }

    add = () => {
     this.setState({
         user:{
             ...this.state.user,
             age: this.state.user.age + 1
         }
     })
    }
}

export default ContextLolClass;